package com.zb.kc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zb.kc.client.UcenterMemberClient;
import com.zb.kc.commonutils.JwtUtils;
import com.zb.kc.commonutils.R;
import com.zb.kc.commonutils.ResultCode;
import com.zb.kc.entity.EduComment;
import com.zb.kc.service.IEduCommentService;
import com.zb.kc.servicebase.exceptionhandler.KgcException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author wanggen
 * @since 2020-04-23
 */
@RestController
@RequestMapping("/eduservice/comment")
public class EduCommentController {

    @Autowired
    private IEduCommentService commentService;

    @ApiOperation(value = "分页查询评论")
    @GetMapping("{current}/{size}")
    public R pageComment(@PathVariable("current") long current,
                         @PathVariable("size") long size,
                         String courseId) {
        Page<EduComment> page = new Page<>(current, size);
        Page<EduComment> page1 = commentService.page(page, new QueryWrapper<EduComment>().eq("course_id", courseId).orderByDesc("gmt_create"));
        return R.ok().dataPage(page1);
    }

    @Autowired
    private UcenterMemberClient memberClient;

    @ApiOperation(value = "添加评论")
    @PostMapping
    public R addCommment(@RequestBody EduComment comment, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        // 如果用户没有登录
        if (StringUtils.isEmpty(memberId)) {
            throw new KgcException(ResultCode.UNLOGINERR);
        }
        comment.setMemberId(memberId);
        // TODO 调用ucenter接口获取用户基本信息
        Map<String, Object> userLessInfo = memberClient.getUserLessInfo(memberId);
        comment.setNickname((String) userLessInfo.get("nickname"));
        comment.setAvatar((String) userLessInfo.get("avatar"));
        commentService.save(comment);
        return R.ok();
    }

}
